#include "dataframe.h"



DataFrame::DataFrame()
    :filePath(),chunk_size(-1),stream(nullptr), handle(nullptr)
{

}

DataFrame::DataFrame(DataFrame&& other)
    :filePath(other.filePath), chunk_size(other.chunk_size),
      handle(other.handle),stream(other.stream)
{
    other.handle = nullptr;
    other.stream = nullptr;
}

DataFrame::~DataFrame(){
    close();
}

bool DataFrame::load (const QString &filePath, int size)
{
    close();
    this->filePath = filePath;
    this->chunk_size = size;
    handle = new QFile(filePath);
    if(handle->open( QFileDevice::ReadOnly | QIODevice::Text )){
        stream = new QTextStream(handle);
        return true;
    }
    return false;
}

QVariantList DataFrame::get_chunk (int size)
{
    if(size != -1)
        this->chunk_size = size;

    QVariantList lines;

    if(handle->isOpen ())
    {
        size = chunk_size;
        while ( size && stream && !stream->atEnd ()) {
            lines += stream->readLine().trimmed ();
            --size;
        }
    }
    return lines;
}

QHash<QString, QVariantList> DataFrame::get_chunk (int size, int left)
{
    if(size != -1)
        this->chunk_size = size;

    QHash<QString, QVariantList> hash;

    auto regExp = QRegExp("[^\\d]+");
    if(handle->isOpen ())
    {
        size = chunk_size;
        while ( size && stream && !stream->atEnd ()) {
            QString phone = stream->readLine();
            if(phone.size () > left){
                phone.remove (regExp);
            }else{
                continue;
            }
            hash[phone.left (left)] << phone;
            --size;
        }
    }
    return hash;
}
